/**
 * JAVACC DEMO 1.0
 * @copy right apache company All rights reserved. 
 * @Package com.apache.rpc.server.impl  
 */
package com.apache.rpc.server.impl;

import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.apache.api.api.ApiService;
import com.apache.api.entity.BaseEntity;
import com.apache.api.manager.PluginConnector;
import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultEntity;
import com.apache.database.constant.SpringContextLoader;
import com.apache.database.constant.Validator;
import com.apache.exception.ServiceException;
import com.apache.rpc.InternalService;
import com.apache.rpc.util.XMLMapParse;

/**
 * description:  
 * @author Hou Dayu 创建时间：2015-9-16  
 * @Copyright(c)2014:
 */
public class InternalServiceImpl implements InternalService {

	private Logger log = Logger.getLogger(InternalServiceImpl.class);
	private List<PluginConnector> plugins;

	/**
	 * TODO 简单描述该方法的实现功能（可选）.  
	 * @see com.apache.rpc.InternalService#doService(java.lang.String)  
	 */
	public ResultEntity doService(String params) {
		ParamsVo<BaseEntity> pvo = new ParamsVo<BaseEntity>();
		if (!params.startsWith("<?xml")) {
			params = XMLMapParse.instance().jsonToXMl(params);
		}
		pvo.setKey(params);
		ResultEntity result = null;
		if (Validator.isEmpty(plugins)) {
			result = getResultEntity("没有指定参数解析器");
			return result;
		}
		try {
			ParamsVo<BaseEntity> vo = new ParamsVo<BaseEntity>();
			for (PluginConnector plugin : plugins) {
				plugin.execute(pvo);
			}
			Map<String, Object> headMap = (Map<String, Object>) pvo.getParams("headMap");
			Map<String, Object> bodyMap = (Map<String, Object>) pvo.getParams("bodyMap");
			vo.setMethodKey(headMap.get("MethodCode").toString());
			vo.setParams(bodyMap);
			ApiService service = (ApiService) SpringContextLoader.getBean(headMap.get("BeanId").toString());
			result = service.doService(vo);
		} catch (Exception e) {
			log.error(e);
			throw new ServiceException("执行方法出错", e);
		}
		return result;
	}

	public void setPlugins(List<PluginConnector> plugins) {
		this.plugins = plugins;
	}

	private ResultEntity getResultEntity(String message) {
		ResultEntity resultEntity = new ResultEntity();
		resultEntity.setResult("false");
		resultEntity.setMessage(message);
		//resultEntity.setEntity("");
		return resultEntity;
	}
}
